/**
* Copyright @ 2023 iAuto (Shanghai) Co., Ltd.
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are NOT permitted except as agreed by
* iAuto (Shanghai) Co., Ltd.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/



import dayjs from 'dayjs';
import {FORMAT_DATEMINUTE, FORMAT_DATETIME, PAGE_SIZE_OPTIONS} from './constant';
import { message } from 'antd';
import { uploadFile, downLoadFile, uploadSignedUrl, getUploadSignedUrl } from '@/services/soa/file';
import BMF from 'browser-md5-file';

/**
 * @description 展示分页总数
 * @param total
 * @param range
 */
export const showTotal = (total: number) => `总共 ${total} 个项目`;

/**
 * @description 展示分页总数
 * @param pagination
 * @param current 如果传入current，则去覆盖pagination的current
 * @param pageSize 如果传入pageSize，则去覆盖pagination的pageSize
 * @returns
 */
export const iAutoPagination = (pagination: any, current?: number, pageSize?: number) => {
  const res = {
    ...pagination,
    showTotal,
    showSizeChanger: true,
    // showQuickJumper: true,
    pageSizeOptions: PAGE_SIZE_OPTIONS,
  };
  if (current && pageSize) {
    return {
      ...res,
      current,
      pageSize,
    };
  }
  return res;
};

/**
 * @description 获取格式化时间
 * @param param 时间
 * @param format 格式
 * @return 格式化后的时间 默认到时分秒
 */
export const getDateTime = (
  param: string | number | Date | undefined,
  format = FORMAT_DATETIME,
): string => {
  if (param && dayjs(param).isValid()) {
    return dayjs(param).format(format);
  }
  return '';
};

/**
 * @description 获取格式化时间
 * @param param 时间
 * @param format 格式
 * @return 格式化后的时间 默认到时分
 */
export const getDateMinute = (
  param: string | number | Date | undefined,
  format = FORMAT_DATEMINUTE,
): string => {
  if (param && dayjs(param).isValid()) {
    return dayjs(param).format(format);
  }
  return '';
};

/**
 @description 上传前的验证
 @param file
 @param format
 @param size
 */
export const imageBeforeUploadHandle: any = (
  file: any,
  format = ['jpg', 'jpeg', 'png'],
  size = 5,
) => {
  return new Promise((resolve) => {
    const typeArray = format.map((obj) => `image/${obj}`);
    const prefix = file.name.toLowerCase().substring(0, file.name.lastIndexOf('.'));

    if (prefix.length > 32) {
      message.error('文件名称长度应在1-32位之间');
      return false;
    }
    if (!typeArray.includes(file.type)) {
      message.error(`上传文件类型只能为${format.join('/')}`);
      return false;
    }
    const isLtM = file.size / 1024 / 1024 < size;
    if (!isLtM) {
      message.error(`请上传小于${size}M的图片`);
      return false;
    }
    return resolve(true);
  });
};

/**
 @description 自定义上传
 @param info
 @param storageType
 @param callback
 */
export const customHandle = (info: any, storageType = 'OFFICIAL_WEBSITE', callback: any) => {
  console.log(info);
  const bmf = new BMF();
  bmf.md5(info.file, (err: any, md5: any) => {
    const formData = new FormData();
    formData.append('file', info.file);
    uploadFile(formData, {
      fileMd5: md5,
      storageType,
      file: info.file,
    }).then((r) => {
      if (r?.data?.uuid) {
        console.log(r);
        info.onSuccess(r, info.file);
        callback(info, r);
      } else {
        info.onError(r);
      }
    });
  });
};

/**
 @description 自定义上传 预上传地址上传
 @param info
 @param callback
 */
 export const customPreHandle = (info: any, callback: any) => {
  console.log(info);
  const bmf = new BMF();
  bmf.md5(info.file, async (err: any, md5: any) => {
    const { data, statusCode, statusMessage } = await getUploadSignedUrl({ fileName: info?.file?.name, md5 })
    if (statusCode === '0') { // 请求成功
      try {
        // 开发网掉不通
        if (process.env.NODE_ENV !== "development") {
          // 上传文件
          await uploadSignedUrl(data.url, info.file)
        }
      } catch (error) {
        console.log("🚀 ~ file: utils.ts ~ line 145 ~ bmf.md5 ~ error", error)
      } finally {
        callback(info, data)
      }
    } else {
      message.warning(statusMessage);
    }

  });
};

/**
 * @description 0 否 1 是
 * @param param
 */
export const get01Text = (param?: number) => {
  if (param === undefined) {
    return '';
  }
  return param === 0 ? '否' : '是';
};

/**
 * @description 分页参数
 * @param current
 * @param pageSize
 */
export const paginationParams = (current: number, pageSize: number) => {
  return {
    current,
    pagesize: pageSize,
  };
};

/**
 * @description 请求第一页,如果已经是第一页,则依然请求第一页
 * @param tableProps
 * @param params
 */
export const refreshOrGoPrePage = ({ tableProps, params }: any) => {
  const { dataSource, pagination, onChange } = tableProps;
  const { current, total, pageSize } = pagination;

  if (dataSource.length === 1 && current === Math.ceil(total / pageSize)) {
    if (onChange) {
      onChange({ ...params[0], current: current - 1 || 1 });
    }
  } else {
    onChange({ ...params[0] });
  }
};

/**
 * @description 文件下载
 * @param uuid
 * @param name
 */
export const downLoad = (uuid:any, name: any) => {
  downLoadFile(uuid).then((res:any) => {
    if (res?.data?.presignedDownloadUrl) {
      const a = document.createElement('a');
      a.href = res?.data?.presignedDownloadUrl;
      a.download = name;
      a.style.display = 'none';
      document.body.appendChild(a);
      a.click();
      document.body.removeChild(a);
    }
  })
}
